package com.jiangxiaofei.citycloud.activity.recruit;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.TimePickerView;
import com.blankj.utilcode.util.EmptyUtils;
import com.jiangxiaofei.citycloud.R;
import com.jiangxiaofei.citycloud.adapter.RetruitWorkLabelAdapter;
import com.jiangxiaofei.citycloud.base.BaseActivity;
import com.jiangxiaofei.citycloud.bean.JobBean;
import com.jiangxiaofei.citycloud.bean.WorkLabelBean;
import com.jiangxiaofei.citycloud.constants.Constants;
import com.jiangxiaofei.citycloud.constants.StringConstants;
import com.jiangxiaofei.citycloud.event.LabelMessage;
import com.jiangxiaofei.citycloud.event.RefreshMessage;
import com.jiangxiaofei.citycloud.mvp.RecruitConstant;
import com.jiangxiaofei.citycloud.mvp.RecruitPersenter;
import com.jiangxiaofei.citycloud.param.AddJobsParam;
import com.jiangxiaofei.citycloud.util.DateUtils;
import com.jiangxiaofei.citycloud.view.FullyGridLayoutManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

/**
 * Created by Administrator on 2017/9/7 0007.
 * 劳务信息发布页面
 */

public class RecruitFindWorkPublishActivity extends BaseActivity implements RecruitConstant.AddJobInfoView, View.OnClickListener
        , RecruitConstant.UpdateJobView, RecruitConstant.GetJobInfoView {
    Button btn_cannel, btn_ok;
    @InjectView(R.id.find_work_et_work_other)
    EditText findWorkEtWorkOther;
    @InjectView(R.id.find_work_rb_discuss)
    RadioButton findWorkRbDiscuss;
    @InjectView(R.id.find_work_rb_pay)
    RadioButton findWorkRbPay;
    @InjectView(R.id.find_work_et_money)
    EditText findWorkEtMoney;
    @InjectView(R.id.find_work_rg_pay)
    RadioGroup findWorkRgPay;
    @InjectView(R.id.find_work_et_phone)
    EditText findWorkEtPhone;
    @InjectView(R.id.find_work_et_user_name)
    EditText findWorkEtUserName;
    @InjectView(R.id.find_work_btn_pulish)
    Button findWorkBtnPulish;
    @InjectView(R.id.find_work_tv_work_label)
    TextView findWorkTvWorkLabel;
    @InjectView(R.id.tv_description)
    EditText findWorkEtWorkDescription;
    @InjectView(R.id.find_work_et_location)
    EditText findWorkEtLocation;
    @InjectView(R.id.do_tv_bengin_date)
    TextView doTvBenginDate;
    @InjectView(R.id.do_tv_end_date)
    EditText doTvEndDate;
    private RecyclerView recyConverage;
    private RetruitWorkLabelAdapter adapter;
    private List<WorkLabelBean> labelList;
    private PopupWindow popupSelectWorkLabel;
    private RecruitConstant.AddJobInfoPersenter addJobInfoPersenter;
    private RecruitConstant.UpdateJobPerssenter updateJobPerssenter;
    private RecruitConstant.GetJobInfoPersenter getJobInfoPersenter;
    private AddJobsParam param;
    private String intentType;
    private int workid;

    @Override
    protected void initView(Bundle savedInstanceState) {
        mActivity = this;
        mContext = this;
        setContentView(R.layout.activity_recruit_find_work_publish_layout);
        ButterKnife.inject(this);
        initTitle();
        addJobInfoPersenter = new RecruitPersenter(mContext, (RecruitConstant.AddJobInfoView) mActivity);
        updateJobPerssenter = new RecruitPersenter(mContext, (RecruitConstant.UpdateJobView) mActivity);
        getJobInfoPersenter = new RecruitPersenter(mContext, (RecruitConstant.GetJobInfoView) mActivity);
        param = new AddJobsParam();
        initPopup();
        EventBus.getDefault().unregister(this);
        Intent intent = getIntent();
        intentType = intent.getStringExtra(StringConstants.INTENTTYPE);
        workid = intent.getIntExtra(StringConstants.WORKID, 0);
        if (isUpdate()) {
            getJobInfoPersenter.getJobInfo();
            findWorkBtnPulish.setText("更\t新");
        }
    }

    boolean isUpdate() {
        return EmptyUtils.isNotEmpty(intentType) && intentType.equals(StringConstants.UPDATE);
    }

    @Override
    protected void setListener() {
        setCTitle("劳务需求页面");
        setLeftOneBg(R.drawable.ic_back);
    }

    @Override
    protected void processLogic(Bundle savedInstanceState) {

    }

    //表单验证
    private boolean isFrom() {
        if (param.getRole().length() <= 0) {
            Ts("请选择劳务类型");
            return false;
        }
        if (EmptyUtils.isEmpty(findWorkEtWorkDescription.getText().toString())) {
            Ts("请输入描述");
            return false;
        }
        if (EmptyUtils.isEmpty(findWorkEtLocation.getText().toString())) {
            Ts("请输入工作地点");
            return false;
        }
        if (findWorkRbPay.isChecked()) {
            if (EmptyUtils.isEmpty(findWorkEtMoney.getText().toString())) {
                Ts("请输入工资");
                return false;
            }
        }
        if (EmptyUtils.isEmpty(findWorkEtPhone.getText().toString())) {
            Ts("请输入联系电话");
            return false;
        }
        if (EmptyUtils.isEmpty(findWorkEtUserName.getText().toString())) {
            Ts("请输入联系人");
            return false;
        }
        return true;
    }

    public void Ts(String str) {
        Toast.makeText(mContext, str, Toast.LENGTH_SHORT).show();
    }

    //选择玩工作标签回调监听
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void unpdateList(LabelMessage message) {
        labelList = message.workLableList;
        adapter.notifyDataSetChanged();
    }

    private void initPopup() {
        popupSelectWorkLabel = new PopupWindow();
        View view = LayoutInflater.from(mContext).inflate(R.layout.popup_select_coverage_layout, null);
        popupSelectWorkLabel.setContentView(view);
        popupSelectWorkLabel.setWidth(DrawerLayout.LayoutParams.WRAP_CONTENT);
        popupSelectWorkLabel.setHeight(DrawerLayout.LayoutParams.WRAP_CONTENT);
//        alertPopupView.setTouchable(true);
        popupSelectWorkLabel.setFocusable(false);
        popupSelectWorkLabel.setBackgroundDrawable(new ColorDrawable(0x00000000));
        btn_cannel = view.findViewById(R.id.btn_cannel);
        btn_ok = view.findViewById(R.id.btn_ok);
        btn_cannel.setOnClickListener(this);
        btn_ok.setOnClickListener(this);
        recyConverage = view.findViewById(R.id.do_recy_popup_coverage_layout);
        labelList = new ArrayList<>();
        if (Constants.workLabelList != null && Constants.workLabelList.size() > 0) {
            labelList.addAll(Constants.workLabelList);
        }
        adapter = new RetruitWorkLabelAdapter(mContext, labelList);
        recyConverage.setLayoutManager(new FullyGridLayoutManager(mContext, 4));
        recyConverage.setAdapter(adapter);
    }

    @OnClick({R.id.find_work_tv_work_label, R.id.find_work_btn_pulish,
            R.id.do_tv_bengin_date, R.id.do_tv_end_date, R.id.find_work_rb_discuss
            , R.id.find_work_rb_pay})
    public void Onclick(View v) {
        switch (v.getId()) {
            case R.id.find_work_tv_work_label:
                //选择工作标签
                popupSelectWorkLabel.showAtLocation(mCenterone, Gravity.CENTER, 0, 0);
                break;
            case R.id.find_work_btn_pulish:
//                提交按钮
                setPrama();
                if (isFrom()) {
                    if (isUpdate()) {
                        param.setId(workid);
                        updateJobPerssenter.updateJob();
                    } else {
                        addJobInfoPersenter.addJobInfo();
                    }
                }
                break;
            case R.id.do_tv_bengin_date:
//                开始时间选择
                showPickerView(doTvBenginDate);
                break;
            case R.id.find_work_rb_discuss:
                findWorkEtMoney.setBackground(mContext.getResources().getDrawable(R.drawable.shape_text_border_no));
                findWorkEtMoney.setEnabled(false);
                break;
            case R.id.find_work_rb_pay:
                findWorkEtMoney.setBackground(mCenterone.getResources().getDrawable(R.drawable.shape_text_border));
                findWorkEtMoney.setEnabled(true);
                break;
            default:
                break;
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.btn_cannel:
                //用户选择区域取消
                popupSelectWorkLabel.dismiss();
                break;
            case R.id.btn_ok:
//            用户选择区域确定
                StringBuffer sb = new StringBuffer();
                for (int i = 0; i < labelList.size(); i++) {
                    if (labelList.get(i).isChecked()) {
                        if (sb.length() > 0) {
                            sb.append(",");
                        }
                        sb.append(labelList.get(i).getName());
                    }
                }
                findWorkTvWorkLabel.setText(sb.toString());
                popupSelectWorkLabel.dismiss();
                break;
            default:
                break;
        }
    }

    //    时间选择器
    private void showPickerView(final TextView tv) {
        TimePickerView pvTime = new TimePickerView.Builder(this, (date, v) -> {//选中事件回调
            tv.setText(DateUtils.getStringDateYMD(date));
        })
                .setType(new boolean[]{true, true, true, false, false, false})
                .build();
        pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
        pvTime.show();
    }

    public void setPrama() {
        param.setContacts(findWorkEtUserName.getText().toString());
        param.setDescription(findWorkEtWorkDescription.getText().toString());
        param.setWorkspace(findWorkTvWorkLabel.getText().toString());
        if (EmptyUtils.isNotEmpty(Constants.bdLocation)) {
            param.setLat(String.valueOf(Constants.bdLocation.getLatitude()));
            param.setLog(String.valueOf(Constants.bdLocation.getLongitude()));
        }
        param.setOther(EmptyUtils.isEmpty(findWorkEtWorkOther.getText().toString()) ? ""
                : findWorkEtWorkOther.getText().toString());
        if (findWorkRbPay.isChecked()) {
            param.setPay(Integer.valueOf(findWorkEtMoney.getText().toString()));
        } else {
            param.setPay(0);
        }
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < labelList.size(); i++) {
            if (labelList.get(i).isChecked()) {
                if (sb.length() > 0) {
                    sb.append(",");
                }
                sb.append(labelList.get(i).getId());
            }
        }
        param.setRole(sb.toString());
        param.setUserId(Constants.userId);
        param.setWorkspace(findWorkEtLocation.getText().toString());
        param.setWorkTime(doTvBenginDate.getText().toString() + "," + doTvEndDate.getText().toString());
        param.setPhone(findWorkEtPhone.getText().toString());
    }

    @Override
    public void setData(Object o) {
        Ts("发布成功");
        EventBus.getDefault().post(new RefreshMessage());
        finish();
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void message(String str) {

    }

    @Override
    public AddJobsParam addJobInfo() {
        return param;
    }


    @Override
    public void onSuccess() {
        //更改成功回调
        Toast.makeText(mContext, "更新成功！", Toast.LENGTH_SHORT).show();
        EventBus.getDefault().post(new RefreshMessage());
        finish();
    }

    @Override
    public void onSuccess(Object o) {
        //拉去详情信息回调
        List<JobBean> jobList = (List<JobBean>) o;
        JobBean jobBean;
        if (jobList.size() > 0) {
            jobBean = jobList.get(0);
            findWorkEtWorkDescription.setText(jobBean.getDescription());
            String[] workTime = jobBean.getWorktime().split(",");
            doTvBenginDate.setText(workTime[0]);
            doTvEndDate.setText(workTime[1]);
            findWorkEtUserName.setText(jobBean.getContacts());
            if (Integer.valueOf(jobBean.getPay()) > 0) {
                findWorkRbPay.setChecked(true);
                findWorkEtMoney.setText(jobBean.getPay());
            } else {
                findWorkRbDiscuss.setChecked(true);
            }
            findWorkEtWorkOther.setText(EmptyUtils.isNotEmpty(jobBean.getOther()) ? jobBean.getOther() : "面议");
            findWorkEtPhone.setText(jobBean.getPhone());
            findWorkEtLocation.setText(jobBean.getWorkplace());
            if (Constants.workLabelList != null && Constants.workLabelList.size() > 0) {
                String[] split = jobBean.getRole().split(",");
                StringBuffer sb = new StringBuffer();
                for (int i = 0; i < split.length; i++) {
                    Integer integer = Integer.valueOf(split[i]);
                    for (WorkLabelBean label : Constants.workLabelList) {
                        if (label.getId() == integer) {
                            if (sb.length() > 0) {
                                sb.append(",");
                            }
                            sb.append(label.getName());

                        }
                    }
                }
                findWorkTvWorkLabel.setText(sb.toString());//工作标签
            }
        }
    }

    @Override
    public int getJobInfo() {
        return workid;
    }

    @Override
    public AddJobsParam updateJob() {
        return param;
    }
}
